package com.googlecode.stemwijzer.client.presenter;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.Place;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
import com.googlecode.stemwijzer.client.StemwijzerServiceAsync;
import com.googlecode.stemwijzer.client.event.ExceptionEvent;
import com.googlecode.stemwijzer.client.event.RegistrationEvent;

public class RegistrationPresenter extends
		AbstractPresenter<RegistrationPresenter.Display> {

	public interface Display extends WidgetDisplay {
		public HasText getName();

		public HasClickHandlers getSendRegistration();
	}

	private final StemwijzerServiceAsync service;

	public static final Place PLACE = new Place("RegistrationPresenter");

	@Inject
	public RegistrationPresenter(Display display, EventBus eventBus,
			StemwijzerServiceAsync service) {
		super(display, eventBus);
		this.service = service;

		bind();
	}

	@Override
	public Place getPlace() {
		return PLACE;
	}

	@Override
	protected void onBind() {
		super.onBind();

		display.getSendRegistration().addClickHandler(
				new SendRegistrationClickHandler());
	}

	private final class SendRegistrationClickHandler implements ClickHandler {
		@Override
		public void onClick(final ClickEvent event) {
			display.startProcessing();

			service.registerUser(display.getName().getText(),
					new RegisterUserCallback());
		}
	}

	private final class RegisterUserCallback implements AsyncCallback<Boolean> {
		@Override
		public void onSuccess(Boolean isUserRegistered) {
			display.stopProcessing();
			if (isUserRegistered) {
				eventBus.fireEvent(new RegistrationEvent(display.getName()
						.getText()));
			} else {
				eventBus.fireEvent(new ExceptionEvent(
						"Registratie is niet gelukt"));
			}
		}

		@Override
		public void onFailure(Throwable t) {
			display.stopProcessing();
			eventBus.fireEvent(new ExceptionEvent("Fout bij registratie", t));
		}
	}
}
